
package com.eva.android;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;

import com.eva.epc.common.file.FileHelper;
import com.x52im.rbchat.MyApplication;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import androidx.annotation.NonNull;

/**
 * 针对Andriod Q（即Andriod 10）及以上版本中跟分区存储限制有关的文件读写辅助方法。
 *
 * @author JackJiang
 * @since 7.2
 */
public class FileHelperQ extends FileHelper
{
    private static String TAG = FileHelperQ.class.getSimpleName() + AndriodVersion.QFlag();

//    public static boolean isFileExistsWithUri(Context pContext, Uri pUri) {
//        if (pUri == null) {
//            return false;
//        } else if (uriStartWithFile(pUri)) {
//            String subPath = pUri.toString().substring(7);
//            return (new File(subPath)).exists();
//        } else if (uriStartWithContent(pUri)) {
//            InputStream is = null;
//
//            boolean var4;
//            try {
//                is = pContext.getContentResolver().openInputStream(pUri);
//                boolean var3 = is != null;
//                return var3;
//            } catch (Exception var14) {
//                var4 = false;
//            } finally {
//                if (is != null) {
//                    try {
//                        is.close();
//                    } catch (IOException var13) {
//                        Log.d(TAG, "isFileExistsWithUri IOException");
//                    }
//                }
//
//            }
//
//            return var4;
//        } else {
//            return pUri.toString().startsWith("/") ? (new File(pUri.toString())).exists() : false;
//        }
//    }

//    public static long getFileLengthWithUri(Context pContext, Uri pUri) {
//        if (pUri == null) {
//            return -1L;
//        } else if (uriStartWithFile(pUri)) {
//            String subPath = pUri.toString().substring(7);
//            File file = new File(subPath);
//            return file.exists() ? file.length() : -1L;
//        } else if (uriStartWithContent(pUri)) {
//            InputStream is = null;
//
//            long var3;
//            try {
//                is = pContext.getContentResolver().openInputStream(pUri);
//                if (is == null) {
//                    var3 = -1L;
//                    return var3;
//                }
//
//                var3 = (long)is.available();
//            } catch (Exception var9) {
//                long var4 = -1L;
//                return var4;
//            } finally {
////                Request.closeInputStream(is);
//                if (is != null) {
//                    try {
//                        is.close();
//                    } catch (IOException var2) {
//                        Log.e(TAG, "closeInputStream", var2);
//                    }
//                }
//            }
//
//            return var3;
//        } else {
//            File file = new File(pUri.toString());
//            return file.exists() ? file.length() : -1L;
//        }
//    }

//    public static boolean isValidateLocalUri(Uri pUri) {
//        return uriStartWithFile(pUri) || uriStartWithContent(pUri);
//    }

    public static boolean uriStartWithFile(Uri pUri) {
        return pUri != null && "file".equals(pUri.getScheme()) && pUri.toString().length() > 7;
    }

    public static boolean uriStartWithContent(Uri srcUri) {
        return srcUri != null && "content".equals(srcUri.getScheme());
    }

    public static String getSuffix(Uri srcUri) {
        return srcUri == null ? null : getSuffix(srcUri.toString());
    }

    public static String getSuffix(String path) {
        if (TextUtils.isEmpty(path)) {
            return null;
        } else {
            int lastDot = path.lastIndexOf(".");
            return lastDot < 0 ? null : path.substring(lastDot + 1);
        }
    }

    public static FileInfo getFileInfoByUri(Context context, Uri uri) {
        if (uriStartWithContent(uri)) {
            return getFileInfoByContent(context, uri);
        } else {
            return uriStartWithFile(uri) ? getFileInfoByFile(uri) : null;
        }
    }

    private static FileInfo getFileInfoByFile(Uri uri) {
        if (uriStartWithFile(uri)) {
            String filePath = uri.toString().substring(7);
            File file = new File(filePath);
            if (file.exists()) {
                FileInfo fileInfo = new FileInfo();
                String name = file.getName();
                fileInfo.setSize(file.length());
                fileInfo.setName(name);
                fileInfo.setLastModified(file.lastModified());
                int lastDotIndex = name.lastIndexOf(".");
                if (lastDotIndex > 0) {
                    String fileSuffix = file.getName().substring(lastDotIndex + 1);
                    fileInfo.setType(fileSuffix);
                }

                return fileInfo;
            } else {
                return null;
            }
        } else {
            Log.e(TAG, "getDocumentByFile uri is not file");
            return null;
        }
    }

    public static FileInfo getFileInfoByFile(File file) {
        if (file != null) {
            if (file.exists()) {
                FileInfo fileInfo = new FileInfo();
                String name = file.getName();
                fileInfo.setSize(file.length());
                fileInfo.setName(name);
                fileInfo.setLastModified(file.lastModified());
                int lastDotIndex = name.lastIndexOf(".");
                if (lastDotIndex > 0) {
                    String fileSuffix = file.getName().substring(lastDotIndex + 1);
                    fileInfo.setType(fileSuffix);
                }

                return fileInfo;
            } else {
                Log.e(TAG, "getFileInfoByFile file is not exist");
                return null;
            }
        } else {
            Log.e(TAG, "getFileInfoByFile file is null");
            return null;
        }
    }

    private static FileInfo getFileInfoByContent(Context context, Uri uri) {
        if (uriStartWithContent(uri)) {
            String[] projection = new String[]{
                    MediaStore.Files.FileColumns.DISPLAY_NAME  //"_display_name"
                    , MediaStore.Files.FileColumns.SIZE        //"_size"
                    , MediaStore.Files.FileColumns.MIME_TYPE   //"mime_type"
                    , MediaStore.Files.FileColumns.DATE_MODIFIED};
            Cursor cursor = null;

//          String name;
            try {
                FileInfo fileInfo = new FileInfo();
                cursor = context.getContentResolver().query(uri, projection, null, null, null);
                if (cursor == null) {
                    Log.e(TAG, "getFileInfoByContent cursor is null");
//                  name = null;
                    return null;//name;
                }

                if (!cursor.moveToFirst()) {
                    return null;
                }

                String name = cursor.getString(0);
                long size = cursor.getLong(1);
                long lastModified = cursor.getLong(3);
                fileInfo.setName(name);
                fileInfo.setSize(size);
                fileInfo.setLastModified(lastModified);
//                FileInfo var15;
                if (TextUtils.isEmpty(name)) {
                    Log.e(TAG, "getFileInfoByContent getName is empty");
                    //var15 = null;
                    return null;//var15;
                }

                int lastDotIndex = name.lastIndexOf(".");
                if (lastDotIndex > 0) {
                    String fileSuffix = name.substring(lastDotIndex + 1);
                    fileInfo.setType(fileSuffix);
                }

                if (cursor.moveToNext()) {
                    Log.e(TAG, "uri is error,cursor has second value,uri is" + uri);
                }

//                var15 = fileInfo;
                return fileInfo;//var15;
            } catch (Exception var13) {
                Log.e(TAG, "getDocumentByContent is error", var13);
//                name = null;
            } finally {
                if (cursor != null) {
                    cursor.close();
                }
            }

            return null;//name;
        } else {
            Log.e(TAG, "getDocumentByContent uri is not content");
            return null;
        }
    }

    /**
     * 打开系统文件选择界面。
     *
     * @param activity 父activity
     * @param requestCode 回调请求码
     */
    public static void chooseSystemFile(@NonNull Activity activity, int requestCode)
    {
        Intent intent = null;
        if(AndriodVersion.isAndroidKitKat_greater$equal()){
            intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
        }
        else{
            intent = new Intent();
            intent.setAction(Intent.ACTION_GET_CONTENT);
        }
        intent.setType("*/*");

        activity.startActivityForResult(intent, requestCode);
    }

    /**
     * 从Uri拷贝文件.
     * <p>
     * 如果目标目录不存在就新建之.
     *
     * @param src 源文件的Uri（因Andriod10及以上系统分存储权限限制，公共目录中的文件无法直接通过File读取
     *            ，只能通过ContentResolver.openFileDescriptor()等方法，相关资料请查阅AndriodQ分区存储适配）
     * @param dest 目标文件，确保文件保存目录位于您APP的私有目录下
     * @return true表示拷贝成功完成，否则不成功
     * @throws Exception
     * @see {@link #copyFile(InputStream, OutputStream)}
     */
    public static boolean copyFile(@NonNull Uri src, @NonNull File dest) throws Exception
    {
        InputStream inStream = null;
        OutputStream outStream = null;
        boolean sucess = false;

        // 如果目标目录不存在就新建之
        if(!dest.getParentFile().exists())
            dest.getParentFile().mkdirs();

        try {
            // 注意AndriodQ及以上版本中公共目录中的文件无法直接通过File读取，只能通过ContentResolver.openFileDescriptor()等
            inStream = MyApplication.getInstance2().getContentResolver().openInputStream(src);
            // 保存的目的文件存储于私有存储，所以可以直接通过File操作
            outStream = new FileOutputStream(dest);

            // 复制文件
            sucess = FileHelper.copyFile(inStream, outStream);
        } finally{
            try {
                if(inStream != null)
                    inStream.close();
                if(outStream != null)
                    outStream.close();
            } catch (Exception ignored) {
            }
        }

        return sucess;
    }

    public static class FileInfo {
        private String name;
        private long size;
        private String type;
        private long lastModified;

        public FileInfo() {
        }

        public String getName() {
            return this.name == null ? "" : this.name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public long getSize() {
            return this.size;
        }

        public void setSize(long size) {
            this.size = size;
        }

        public String getType() {
            return this.type == null ? "" : this.type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public long getLastModified() {
            return lastModified;
        }

        public void setLastModified(long lastModified) {
            this.lastModified = lastModified;
        }
    }
}
